package com.sanerzone.smscenter.biz.task;

import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.entity.SmsReportSync;
import com.sanerzone.smscenter.biz.mapper.SmsReportSyncMapper;
import com.sanerzone.smscenter.biz.utils.TableNameHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 状态异步报告
 * @author zhangjie
 */
@Service
@Lazy(false)
public class SmsReportSyncTask {
	Logger logger = LoggerFactory.getLogger(SmsReportSyncTask.class);

	@Autowired
	private SmsReportSyncMapper smsReportSyncMapper;
	@Autowired
	private SqlSessionFactory sqlSessionFactory;
	/**
	 * 延时一分钟执行一次
	 */
	@Scheduled(cron = "0 0/1 * * * ? ")
	public void execSync()
	{
		SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);

		logger.info("网状提交状态，同步任务执行中...");
		List<SmsReportSync> list = smsReportSyncMapper.findList(new SmsReportSync());
		try {

			if (null != list)
			{

				Map<String,Object> map = null;
				int index = 0;
				for (SmsReportSync para : list)
				{
					index++;
					map = Maps.newHashMap();
					map.put("mtBatch", para.getMtBatch());
					if("DELIVRD".equals(para.getStat())){//成功
						map.put("gatewayStatus", "T100");
					}else{
						map.put("gatewayStatus", "F2" + para.getStat());//失败
					}
					map.put("submitTime", para.getSubmitTime());
					map.put("phone", para.getPhone());
					map.put("reportTime", para.getDoneTime());
					map.put("tableName", "sms_send_" + TableNameHelper.getTableIndex(para.getBizid()));
					int num = sqlSession.update("com.sanerzone.smscenter.biz.mapper.SmsSendMapper.batchUpdateGatewayStatus", map);
					smsReportSyncMapper.delete(para);
					index++;
					if (index % 200 == 0) {
						sqlSession.commit();
					}
					sqlSession.commit();
				}

			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if (sqlSession!=null){
				sqlSession.close();
			}
		}
	}

	public SmsReportSyncMapper getSmsReportSyncMapper() {
		return smsReportSyncMapper;
	}

	public void setSmsReportSyncMapper(SmsReportSyncMapper smsReportSyncMapper) {
		this.smsReportSyncMapper = smsReportSyncMapper;
	}

	public SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
}
